<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 新增角色按钮 -->
        <el-row style="height:60px">
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="showRoleDialog"
          >新增角色</el-button>
        </el-row>
        <el-dialog title="编辑弹层" :visible="roleDialogVisible" @close="closeRoleDialog">
          <!-- 表单内容 -->
          <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="roleForm.description" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button size="small" type="primary" @click="confirmAdd">确定</el-button>
          </el-row>
    </el-dialog>
        <!-- 表格 -->
        <el-table :data="roleList">
          <el-table-column label="序号" width="120" type="index" :index="indexMethod" />
          <el-table-column label="角色名称" width="240" prop="name" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作" width="240" fixed="right">
            <template #default={row}>
                <el-button size="small" @click="assignDialog(row.id)">分配权限</el-button>
                <el-button size="small" @click="compile(row.id)">编辑</el-button>
                <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页组件 -->
          <el-pagination layout="prev,pager,next" :total="total" :page-size="params.pagesize" @current-change="pageChange" />
        </el-row>
      </el-card>
    </div>
    <!-- 分配权限的弹层 -->
    <el-dialog 
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)" 
        :visible="showAssignDialog"
        @close="assignDialogClose"
        @open="assignDialogOpen"
        >
      <!-- 权限点数据展示 -->
      <template #default>
        <!-- 
          props: 定制到底要识别哪个字段的名字 后端返回的不叫label，叫name
          default-expand-all: 默认展开所有项
          show-checkbox: 可选框变为可选的状态
          check-strictly: 父级和子级可以变为独立可选择的
         -->
        <el-tree
          ref="tree"
          :data="permissionData"
          :props="{ label: 'name' }"
          :default-expand-all="true" 
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
      </template>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="assignDialogClose">取消</el-button>
          <el-button type="primary" @click="confirmAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, deleteRole, addRole, getRoleDetail, assignPerm, getRoleDetailById, updateRole } from '@/api/setting'
import { getPermissionList } from '@/api/permisson'
import transTree from '@/utils/transTree'
export default ({
  data() {
    return {
      // 展示第几页，每页展示多少条，
      params: {
        page: 1,
        pagesize: 5
      },
      roleList: [],
      total: 0,
      roleDialogVisible: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules:{
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      curId: null,
      showAssignDialog: false,
      permissionData: []  // 权限树形数据
    }
  },
  mounted() {
    // 自调用
    this.fetchRoleList()
  },
  methods: {
    // 获取角色数据
    async fetchRoleList() {
      const res = await getRoleList(this.params)
      // 获取角色数据
      this.roleList = res.rows
      // 获取总共多少条数
      this.total = res.total
    },
    // 更改页码触发时发生变化
    pageChange(page) {
      // Page是当前点击的页码
      this.params.page = page // 将当前页码赋值给当前的最新页码
      this.fetchRoleList()
    },
    // 删除
    delRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 调用删除接口
        await deleteRole(id)
        // 更新列表
        this.fetchRoleList()
        // 提示用户
        this.$message.success('删除角色成功')
      }).catch()
    },
    // 打开弹窗
    showRoleDialog() {
      this.roleDialogVisible = true
    },
    // 关闭弹窗
    closeRoleDialog(){
      this.roleDialogVisible = false
      this.roleForm = {
        name: '',
        description: ''
      }
      // 移除校验
      this.$refs.roleForm.resetFields()
    },
    confirmAdd() {
       this.$refs.roleForm.validate(async valid => {
        if (valid) {
          // todo login
         if (this.roleForm.id) {
            await updateRole(this.roleForm)
          } else {
            await addRole(this.roleForm)
          }
          // 更新列表
          this.fetchRoleList()
          // 提示用户
          this.$message.success(`${this.roleForm.id ? '更新成功' : '新增成功'}`)
          this.closeRoleDialog()
        }
      })
    },
    cancel() {
      this.closeRoleDialog()
    },
    indexMethod(index) {
      index++
      return index * 2
    },
    // 编辑功能
    async compile(id) {
      const res = await getRoleDetail(id)
      this.roleForm = res
      this.roleDialogVisible = true
    },
    // 分配权限
    assignDialog(id) {
      this.curId = id
      this.showAssignDialog = true
    },
    assignDialogClose() {
      this.showAssignDialog = false
      this.$refs.tree.setCheckedKeys([])
    },
    async assignDialogOpen() {
      const res = await getPermissionList()
      // transTree 渲染树形结构
      this.permissionData = transTree(res)
      // 获取详情数据
      const detail = await getRoleDetailById(this.curId)
      // 拿到的数据辉县可选列表中
      this.$refs.tree.setCheckedKeys(detail.permIds)
    },
    confirmAssign() {
      assignPerm({
        id: this.curId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('分配权限点成功')
      // 关闭弹框
      this.assignDialogClose()
    }
  }
})
</script>
